package logic

// logic/user_post_history.go

import (
	"bluebell/dao/mysql"
	"bluebell/models"
	"errors"
	"go.uber.org/zap"
	"strconv"
	"time"
)

// RecordUserPostHistory 记录或更新用户帖子观看历史
func RecordUserPostHistory(userID, postID int64) error {
	history := &models.UserPostHistory{
		UserID:   userID,
		PostID:   postID,
		ViewTime: time.Now().Unix(),
	}
	return mysql.CreateOrUpdateUserPostHistory(history)
}

// GetUserPostHistoryList 获取用户观看历史列表
func GetUserPostHistoryList(userID, page, size int64) (*models.GetHistoryListResponse, error) {
	// 1. 获取历史记录
	histories, err := mysql.GetUserPostHistoryList(userID, page, size)
	if err != nil {
		zap.L().Error("获取历史记录失败", zap.Error(err))
		return nil, err
	}

	if len(histories) == 0 {
		return &models.GetHistoryListResponse{
			Count: 0,
			List:  []*models.HistoryDetail{},
		}, nil
	}

	// 2. 获取帖子预览信息
	postIDs := make([]int64, len(histories))
	for i, h := range histories {
		postIDs[i] = h.PostID
	}

	postPreviews, err := mysql.GetPostsPreviewByIDs(postIDs)
	if err != nil {
		zap.L().Error("获取帖子预览失败", zap.Error(err))
		return nil, err
	}

	// 3. 组装响应数据
	details := make([]*models.HistoryDetail, 0, len(histories))
	for _, history := range histories {
		preview, ok := postPreviews[history.PostID]
		if !ok {
			continue // 跳过不存在的帖子
		}

		details = append(details, &models.HistoryDetail{
			PostID:   strconv.FormatInt(history.PostID, 10), // 转为字符串
			Title:    preview.Title,
			Preview:  preview.Content + "...", // 添加省略号
			ViewTime: history.ViewTime,
		})
	}

	// 4. 获取总数
	count, err := mysql.GetUserPostHistoryCount(userID)
	if err != nil {
		zap.L().Error("获取历史记录总数失败", zap.Error(err))
		return nil, err
	}

	return &models.GetHistoryListResponse{
		Count: count,
		List:  details,
	}, nil
}

// DeleteSingleHistory 删除单条历史记录
func DeleteSingleHistory(historyID, userID int64) error {
	// 验证记录是否属于该用户
	exists, err := mysql.CheckHistoryOwnership(historyID, userID)
	if err != nil {
		return err
	}
	if !exists {
		return errors.New("history record does not exist or belongs to another user")
	}

	return mysql.DeleteHistoryByID(historyID)
}

// ClearUserHistory 清空用户所有历史记录
func ClearUserHistory(userID int64) error {
	return mysql.DeleteAllHistoryForUser(userID)
}
